import { defineStore } from 'pinia'
import { login as loginApi } from '@/services/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: null,
    userInfo: null
  }),
  getters: {
    isLoggedIn: (state) => !!state.token
  },
  actions: {
    async login(username, password) {
      try {
        const res = await loginApi(username, password)
        if (res.code === '200') {
          this.token = res.data.token
          this.userInfo = res.data.userInfo
          return true
        } else {
          ElMessage.error(res.message || '登录失败')
          return false
        }
      } catch (error) {
        ElMessage.error('登录失败，请稍后重试')
        return false
      }
    },
    logout() {
      this.token = null
      this.userInfo = null
    }
  },
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'userInfo']
  }
})